package main

import (
    "os/signal"
    "log"
    "os"
    "time"
    "io/ioutil"
    "fmt"
    "syscall"
)

var mainlog *log.Logger = nil
func setupLog() {
    f, err := os.OpenFile("/var/log/vmrobot.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
    if err != nil {
        log.Fatal("open log file failed.", err)
        return
    }
    mainlog = log.New(f, "", log.Ldate|log.Ltime)
}

func setupFatalLog() error {
    f, err := os.OpenFile("/var/log/vmrobot.fatal.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
    if err != nil {
        log.Fatal("open log file failed.", err)
        return err
    }
    syscall.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
    return nil
}

func savePid() {
    s := fmt.Sprintf("%d", os.Getpid())
    err := ioutil.WriteFile("/var/run/vmrobot.pid", []byte(s), 0644)
    if err != nil {
        mainlog.Println("write pid file failed.", err)
    }
}

func signalHandle() {
    for {
        sig := <- GSignal
        if sig == syscall.SIGHUP {
            //todo
        }
    }
}

var GSignal = make(chan os.Signal, 1)

func main() {
    setupLog()
    setupFatalLog()
    savePid()
    
    go signalHandle()
    signal.Notify(GSignal, syscall.SIGHUP)
    
    g_config = loadConfig()

    if g_config.Mode == EMODE_PUSH {
        mainlog.Println("running with push mode")
        go initListen(g_config.Listen)
        for {
            time.Sleep(1 * time.Second)
        }
    }else if g_config.Mode == EMODE_PULL {
        mainlog.Println("running with pull mode")
        for {
            mainlog.Println("timeInterval:", g_config.timeInterval, "(s)")
            time.Sleep(time.Duration(g_config.timeInterval) * time.Second)
            startGet()
        }
    }
}
